package Server;

/**
 *
 * @author Daniel
 */
import java.net.*;
import java.io.*;
import java.util.*;

public class Client implements Runnable
{
    private Socket connection;
    private Thread clientThread;
    private OutputStream outStream;
    private InputStream inStream;
    String message=null;
    private int loginStatus=0;

    
    public Client(Socket connection, int id)
    {
        //Construct our we client handler
        this.connection     = connection;
        this.clientThread   = new Thread(this, "" + id);
        try
        {
            this.outStream      = new BufferedOutputStream(this.connection.getOutputStream());
            this.inStream = new BufferedInputStream((this.connection.getInputStream()));

            System.out.println("Connection request received");
            //Make first contact
            this.initConn();
            //Wait for message and respond
            //Handle the sh*t out of this mofo.
            System.out.println("Client thread started. You are thread "+ this.clientThread.getId() );
        }
        catch(IOException ioe)
        {
            System.out.println("IO exception while attempting to setup outputstream");
            System.out.println("Error: " + ioe);
            System.exit(3);
        }          
        this.clientThread.start();

    }
    
    public void run()
    {

        String outMessage = "Got it";
        byte [] buff = new byte[500];
        int messageLength=0;

        //keep accepting input
        while(true){
            try {
                //read input message
                inStream = this.connection.getInputStream();
                messageLength = inStream.read(buff);
                message = new String(buff,0,messageLength);
                //display message
                processMessage(message);

            } catch (SocketException se){
                this.clientThread.stop();
                System.out.println("Client Disconnected. Stopping Thread...");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void processMessage(String message){

        //get Process Letter
        char process = message.charAt(2);
        message = message.replace('|',' ');

        //login
        if(process == 'L'){
           int spaces = 0;
           int newId=0;
           String id="";
           char current;
           String name = "";

           for(int i=0;i<message.length();i++){

              current = message.charAt(i);

               if(current==' '){
                   spaces++;
               }
               else if(spaces == 2){
                    id+=current;
               }
               if(spaces == 3 || spaces == 4){
                   name+=current;
               }
           }
           newId = Integer.parseInt(id);
           process = 0;
           checkCustomer(newId,name);
        }
        //search
        else if(process =='S'){
            //search book method
        }
        //register
        else if(process == 'R'){
            //register customer method
        }
    }
    //validate customer method
    private void checkCustomer(int id, String name){

        String outMessage = "";
        boolean found = false;
        name = name.substring(1,name.length());

        for(CustRec customer : Server.bsd.getCusts()){

            if(customer.getName().equals(name) && customer.getCustID() == id){
                loginStatus=1;
                found = true;
            }
        }
        if(found){
            outMessage += loginStatus+"|LR|T|%";
        }
        else{
            outMessage += loginStatus+"|LR|F|%";
        }
        writeMessage(outMessage);
    }
    
    public Socket getSocket(){
        return this.connection;
    }

    private boolean writeMessage(String message)
    {
        try
        {
            System.out.println(message);
            outStream = this.connection.getOutputStream();
            outStream.write(message.getBytes());
        }
        catch(IOException ioe)
        {
            System.out.println("IOException when trying to write message");
            System.out.println("IOE from thread/client: " + this.clientThread.getId());
            System.out.println("Error: " + ioe);
            return false;
        }
        return true;
    }

    private void initConn()
    {
        //Send client it's ID and confirm connection
        this.writeMessage("Y");
    }

}